package controllers

import (
	"fmt"
	"nway_dsr/dsr/models"
	"nway_dsr/dsr/utils/export_excel"
	"strconv"
	"strings"
	"time"

	"github.com/tealeg/xlsx"
)

type CdrController struct {
	BaseController
}

func (this *CdrController) Cdr() {
	this.Data["pageTitle"] = "通话详单"
	this.Data["type"], _ = this.GetInt("type")
	this.display()
}

func (this *CdrController) Flow_content() {
	this.Data["pageTitle"] = "通话记录"
	this.Data["call_id"] = this.GetString("call_id")
	this.Data["other_uuid"] = this.GetString("other_uuid")
	this.Data["off_line"] = this.GetString("off_line")
	this.Data["off_line1"] = this.GetString("off_line1")
	arr := strings.Split(this.GetString("audio"), "recordings/")
	this.Data["audio"] = "/vad_dir/" + arr[len(arr)-1]
	this.display()
}
func (self *CdrController) ContentTableAllList() {
	//列表
	call_id := self.GetString("call_id")
	off_line := self.GetString("off_line")
	if call_id == "excel" {
		weixian, youliang := self.keywordsLists()
		xlFile, err := xlsx.OpenFile("./upload/excel/file.xlsx")
		if err != nil {
			fmt.Println("open excel error :", err.Error())
		}
		list := []map[string]interface{}{}
		var count int64
		var a, b, s string
		for _, sheet := range xlFile.Sheets {
			for _, row := range sheet.Rows {
				//fmt.Println("===============")
				//fmt.Println(row.Cells)
				if len(row.Cells) == 0 {
					continue
				}
				row1 := row.Cells[0].String()
				row2 := row.Cells[1].String()
				count++
				if row1 != "" {
					_, fail, fine := models.AiGetKeyword(row1)
					fmt.Println(fail, fine)
					if fine != "" || fail != "" {
						a, b, s = jishuanAbs(fine, fail, "a", weixian, youliang, a, b, s)
					}
					list = append(list, map[string]interface{}{"ai_speak": row1, "people_speak": "-1", "fine": fine, "fail": fail, "id": count + 1})
				} else {
					_, fail, fine := models.AiGetKeyword(row2)
					fmt.Println(fail, fine)
					if fine != "" || fail != "" {
						a, b, s = jishuanAbs(fine, fail, "b", weixian, youliang, a, b, s)
					}
					list = append(list, map[string]interface{}{"people_speak": row2, "ai_speak": "-1", "fine": fine, "fail": fail, "id": count + 1})
				}
			}
		}
		if err == nil {
			self.ajaxList("成功", MSG_OK, count, map[string]interface{}{"data": list, "a_score": a, "b_score": b, "score": s})
		}
	}

	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	orderby := "dsr_time"
	if off_line == "true" { //如果是离线的质检，需要判断他的时间是根据speak_second判断的
		orderby = "speak_second"
	}
	result, count := models.AiFlowContentGetListAll(orderby, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		if v.Callee == "true" {
			row["ai_speak"] = v.Content
			row["people_speak"] = "-1"
		} else {
			row["people_speak"] = v.Content
			row["ai_speak"] = "-1"
		}
		row["fine"] = v.Fine
		row["fail"] = v.Fail
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}
func (self *CdrController) GetExcel() {
	call_id := self.GetString("call_id")
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	result, _ := models.AiFlowContentGetListAll("dsr_time", filters...)

	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		if v.Caller == "true" { //a路
			row["ai_speak"] = v.Content
			row["people_speak"] = "-1"
		} else {
			row["people_speak"] = v.Content
			row["ai_speak"] = "-1"
		}
		row["fine"] = v.Fine
		row["fail"] = v.Fail
		list[k] = row
	}
	export_excel.ExportExcel(list)
	self.ajaxMsg("成功", MSG_OK)

	//
}
func (self *CdrController) Flowcdr() {
	self.Data["pageTitle"] = "实时监控"
	self.Data["callid"] = self.GetString("callid")
	self.Data["off_line"] = self.GetString("off_line")
	self.Data["off_line1"] = self.GetString("off_line1")
	weixian := []string{}
	for _, v := range models.AiFlowContentGetWeixian() {
		weixian = append(weixian, v.Keyword)
	}
	self.Data["weixian"] = weixian
	youliang := []string{}
	for _, v := range models.AiFlowContentGetYouliang() {
		youliang = append(youliang, v.Keyword)
	}
	self.Data["youliang"] = youliang
	success := []string{}
	for _, v := range models.AiFlowContentGetSuccess() {
		success = append(success, v.Keyword)
	}
	self.Data["success"] = success
	self.display()
}
func (self *CdrController) KeywordList() {
	weixian := []map[string]interface{}{}
	lists := map[string]interface{}{}
	for _, v := range models.AiFlowContentGetWeixian() {
		var obj = map[string]interface{}{"keyword": v.Keyword, "score": v.Score}
		weixian = append(weixian, obj)
	}
	lists["weixian"] = weixian
	youliang := []map[string]interface{}{}
	for _, v := range models.AiFlowContentGetYouliang() {
		var obj = map[string]interface{}{"keyword": v.Keyword, "score": v.Score}
		youliang = append(youliang, obj)
	}
	lists["youliang"] = youliang
	success := []string{}
	for _, v := range models.AiFlowContentGetSuccess() {
		success = append(success, v.Keyword)
	}
	lists["success"] = success
	self.ajaxList("成功", 0, 0, lists)
}

func (self *CdrController) keywordsLists() ([]map[string]interface{}, []map[string]interface{}) {
	weixian := []map[string]interface{}{}
	lists := map[string]interface{}{}
	for _, v := range models.AiFlowContentGetWeixian() {
		var obj = map[string]interface{}{"keyword": v.Keyword, "score": v.Score}
		weixian = append(weixian, obj)
	}
	lists["weixian"] = weixian
	youliang := []map[string]interface{}{}
	for _, v := range models.AiFlowContentGetYouliang() {
		var obj = map[string]interface{}{"keyword": v.Keyword, "score": v.Score}
		youliang = append(youliang, obj)
	}
	lists["youliang"] = youliang
	success := []string{}
	for _, v := range models.AiFlowContentGetSuccess() {
		success = append(success, v.Keyword)
	}
	lists["success"] = success
	return weixian, youliang
}

func (self *CdrController) ContentTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	callee := self.GetString("callee")
	caller := self.GetString("caller")
	off_line := self.GetString("off_line")
	a := self.GetString("a_billsec")
	b := self.GetString("b_billsec")
	wordType := self.GetString("wordType")
	call_id := self.GetString("call_id")
	start := self.FormatTimes(self.GetString("startDate"))
	end := self.FormatTimes(self.GetString("endDate"))

	self.pageSize = limit
	//查询条件
	filters := make([]string, 0)
	if start != "0001-01-01 00:00:00" && end != "0001-01-01 00:00:00" {
		filters = append(filters, "start_time__lte", end)
		filters = append(filters, "end_time__gte", start)
	} else {
		timeStr := time.Now().Format("2006-01-02")
		filters = append(filters, "start_time__icontains", timeStr)
	}
	if callee != "" { //被叫
		filters = append(filters, "callee__exact", callee)
	}
	if caller != "" { //主叫
		filters = append(filters, "caller__exact", caller)
	}
	if a != "" { //a路时长
		filters = append(filters, "a_billsec__gte", a)
	}
	if b != "" { //b路时长
		filters = append(filters, "b_billsec__gte", b)
	}
	if call_id != "" { //call_id
		filters = append(filters, "call_id__exact", call_id)
	}
	filters = append(filters, "offline_qc__exact", off_line) //判断是不是    离线 的
	result := []*models.DsrCdr{}
	var count int64
	if wordType == "1" {
		result, count = models.CdrGetList1(page, self.pageSize, "fail_info", filters...)
	} else if wordType == "2" {
		result, count = models.CdrGetList1(page, self.pageSize, "fine_info", filters...)
	} else {
		result, count = models.CdrGetList(page, self.pageSize, filters...)
	}
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["account_id"] = v.Account_id
		row["callee"] = v.Callee
		row["caller"] = v.Caller
		if len(v.Start_time) > 20 {
			row["start_time"] = v.Start_time[:20]
		} else {
			row["start_time"] = v.Start_time
		}
		if len(v.End_time) > 20 {
			row["end_time"] = v.End_time[:20]
		} else {
			row["end_time"] = v.End_time
		}
		row["duration"] = v.Duration
		row["record_base"] = v.Record_base
		row["record_path"] = v.Record_path
		row["call_id"] = v.Call_id
		if len(v.A_answer_time) > 20 {
			row["a_answer_time"] = v.A_answer_time[:20]
		} else {
			row["a_answer_time"] = v.A_answer_time
		}
		if len(v.B_answer_time) > 20 {
			row["b_answer_time"] = v.B_answer_time[:20]
		} else {
			row["b_answer_time"] = v.B_answer_time
		}

		row["a_billsec"] = v.A_billsec
		row["b_billsec"] = v.B_billsec
		row["b_caller"] = v.B_caller
		row["b_callee"] = v.B_callee
		row["other_uuid"] = v.Other_uuid
		row["a_score"] = v.A_score
		row["b_score"] = v.B_score
		row["score"] = v.Score
		row["offline_qc"] = v.Offline_qc
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *CdrController) Flow_content_list() {
	weixian, youliang := self.keywordsLists()
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	call_id := self.GetString("call_id")
	other_uuid := self.GetString("other_uuid")
	//查询条件
	//filters := make([]interface{}, 0)
	//filters = append(filters, "call_id", call_id)
	result, count := models.FlowContentGetListByCdrId(page, self.pageSize, call_id, other_uuid)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["call_id"] = v.Call_id
		row["callee"] = v.Callee
		row["caller"] = v.Caller
		row["record"] = v.Record_base + v.Record_path
		row["dsr_time"] = v.Dsr_time[:20]
		row["content"] = v.Content
		row["score"] = 0
		var i = 0
		if v.Callee == "true" {
			row["call"] = "b路"
		} else if v.Caller == "true" {
			row["call"] = "a路"
		}
		row["fine"] = v.Fine
		row["fail"] = v.Fail
		if v.Fine != "" {
			arr := strings.Split(v.Fine, ",")
			for _, b := range arr {
				for _, v := range youliang {
					if b == v["keyword"] {
						val, _ := v["score"]
						i += val.(int)
						continue
					}
				}
			}
		}
		if v.Fail != "" {
			arr := strings.Split(v.Fail, ",")
			for _, b := range arr {
				for _, v := range weixian {
					if b == v["keyword"] {
						val, _ := v["score"]
						i -= val.(int)
						continue
					}
				}
			}
		}
		row["score"] = i
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *CdrController) ContentTableOne() {
	//列表
	call_id := self.GetString("call_id")
	off_line := self.GetString("off_line")
	off_line1 := self.GetString("off_line1")

	bool, err := models.IsRuntimeByCallId(call_id)
	if err != nil {
		fmt.Println(err.Error())
	}
	if bool == false && off_line1 != "true" {
		self.ajaxMsg("删除数据", MSG_ERR)
		return
	}
	id, _ := self.GetInt64("id")
	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	filters = append(filters, "id__gt", id)
	orderby := "dsr_time"   //默认是 在线识别的
	if off_line == "true" { //如果是离线的质检，需要判断他的时间是根据speak_second判断的
		orderby = "speak_second"
	}
	result, count := models.AiFlowContentGetListAll(orderby, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		if v.Callee == "true" {
			row["ai_speak"] = v.Content
			row["people_speak"] = "-1"
		} else {
			row["people_speak"] = v.Content
			row["ai_speak"] = "-1"
		}
		row["fine"] = v.Fine
		row["fail"] = v.Fail
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}
func (self *CdrController) SelectCallPgCdrRecode() {
	//列表
	uuid := self.GetString("uuid")
	recode, _ := models.SelectCallPgCdr(uuid)
	self.ajaxMsg(recode, MSG_OK)
}

func jishuanAbs(fine, fail, is_b string, weixian, youliang []map[string]interface{}, aa, bb, ss string) (string, string, string) {
	a, _ := strconv.Atoi(aa)
	b, _ := strconv.Atoi(bb)
	s, _ := strconv.Atoi(ss)
	if fine != "" {
		arr := strings.Split(fine, ",")
		for _, v1 := range arr {
			for _, v := range youliang {
				if v1 == v["keyword"] {
					val, _ := v["score"]
					s += val.(int)
					if is_b == "b" { //b路
						b += val.(int)
					} else { //a路
						a += val.(int)
					}
					continue
				}
			}
		}
	}
	if fail != "" {
		arr := strings.Split(fail, ",")
		for _, v1 := range arr {
			for _, v := range weixian {
				if v1 == v["keyword"] {
					val, _ := v["score"]
					s -= val.(int)
					if is_b == "b" { //b路
						b -= val.(int)
					} else { //a路
						a -= val.(int)
					}
					continue
				}
			}
		}
	}
	return strconv.Itoa(a), strconv.Itoa(b), strconv.Itoa(s)
}
